package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.contast.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import javax.swing.text.html.HTML;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Gallant
 * @create 2020-07-02 18:33
 */
@Component
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath ;

    // 新增方法
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        // 先将套餐进行保存
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            setSetmealAndCheckGroup(setmealId, checkgroupIds);
        }
        this.savePicNameToRedis(setmeal.getImg());
        this.generateMobileStaticHtml();
    }

    // 设置套餐及其检查组
    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmealId);
                map.put("checkgroup_id", checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

    // 将图片名称信息存储到redis缓存中
    private void savePicNameToRedis(String picName) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, picName);
    }

    // 生成静态页面
    public void generateMobileStaticHtml() {
        List<Setmeal> setmealList = this.findAll();
        // 生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        // 生成套餐详情静态页面
        generateMobileSetmealListDetailHtml(setmealList);
    }

    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    public void generateMobileSetmealListDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", this.findById(setmeal.getId()));

            this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    // 分页查询
    public PageResult queryPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        // 设置分页的参数
        PageHelper.startPage(currentPage, pageSize);
        // 调用dao查询所有的套餐
        List<Setmeal> list = setmealDao.findByCondition(queryString);
        // 利用分页插件进行封装
        PageInfo<Setmeal> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        List<Setmeal> setmealList = pageInfo.getList();
        return new PageResult(total, setmealList);
    }

    // 查询所有套餐
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    // 根据id查询
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    // 统计套餐的数量
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }


}
